package controller;

import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Time;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import dao.EventDao;

import modle.Event;
import modle.User;
import view.TaskFrame;
import view.EventPanel;

public class EventController implements ActionListener, ListSelectionListener {

	TaskFrame taskFrame;
	EventPanel eventPanel;
	EventThread eventThread = null;

	public EventController(EventPanel eventPanel) {
		// TODO Auto-generated constructor stub
		taskFrame = eventPanel.getTaskFrame();
		this.eventPanel = eventPanel;
	}

	public void actionPerformed(ActionEvent event) {
		// TODO Auto-generated method stub
		if (event.getSource() == eventPanel.getAddButton())
			addEvent();
		if (event.getSource() == eventPanel.getModifyButton())
			modifyEvent();
		if (event.getSource() == eventPanel.getRemoveButton())
			removeEvent();
		if (event.getSource() == eventPanel.getBrowseButton()) {
			setSoundFile();
		}
	}

	public void addEvent() {
		Event event = new Event();
		getEventFromPanel(event);
		event.setUser(getUser());
		EventDao eventDao = new EventDao();
		if (eventDao.save(event) > 0) {
			event = eventDao.findByEventName(event.getEventName()).get(0);
			getUser().getEvents().add(event);
			eventPanel.getEventTableModel().setData(getUser().getEvents());
			showMessage("Add Event Successfully!");
		} else
			showMessage("Add Event Failed!");
		eventDao.closeConnection();
	}

	private void eventTableIsChosen() {
		// TODO Auto-generated method stub
		int select = eventPanel.getEventTable().getSelectedRow();
		List<Event> events = getUser().getEvents();
		if (select < 0 || select >= events.size())
			return;
		Event event = events.get(select);
		setEventToPanel(event);
		// set component enabled
		eventPanel.getRemoveButton().setEnabled(true);
		eventPanel.getModifyButton().setEnabled(true);
	}

	private void getEventFromPanel(Event event) {
		event.setEventName(eventPanel.getEventNameField().getText());
		event.setEventTime(Time.valueOf(eventPanel.getHourComboBox()
				.getSelectedItem().toString()
				+ ":"
				+ eventPanel.getMinuteComboBox().getSelectedItem().toString()
				+ ":00"));
		// get the value of recycle
		int re = 0;
		if (eventPanel.getMonCheckBox().isSelected())
			re += Event.MONDAY;
		if (eventPanel.getTueCheckBox().isSelected())
			re += Event.TUESDAY;
		if (eventPanel.getWedCheckBox().isSelected())
			re += Event.WEDNESDAY;
		if (eventPanel.getThuCheckBox().isSelected())
			re += Event.THURSDAY;
		if (eventPanel.getFriCheckBox().isSelected())
			re += Event.FRIDAY;
		if (eventPanel.getSatCheckBox().isSelected())
			re += Event.SATURDAY;
		if (eventPanel.getSunCheckBox().isSelected())
			re += Event.SUNDAY;

		event.setEventRecycle(re);
		event.setEventIntroduction(eventPanel.getIntroductionArea().getText());
		if (eventPanel.getSoundCheckBox().isSelected())
			event.setIsSoundAlert((byte) 1);
		else
			event.setIsSoundAlert((byte) 0);
		event.setSoundFilePath(eventPanel.getFileField().getText());
		if (eventPanel.getWindowCheckBox().isSelected())
			event.setIsWindowAlert((byte) 1);
		else
			event.setIsWindowAlert((byte) 0);
	}

	public User getUser() {
		return taskFrame.getUser();
	}

	public void loginSuccessfully() {
		eventPanel.getEventTableModel().setData(getUser().getEvents());
		if (eventThread == null)
			eventThread = new EventThread(getUser().getEvents());
		else
			eventThread.setEvents(getUser().getEvents());
	}

	public void modifyEvent() {
		int select = eventPanel.getEventTable().getSelectedRow();
		List<Event> events = getUser().getEvents();
		if (select < 0 || select >= events.size())
			return;
		Event oldEvent = events.get(select);
		Event newEvent = new Event();
		getEventFromPanel(newEvent);
		newEvent.setEventId(oldEvent.getEventId());
		EventDao eventDao = new EventDao();
		if (eventDao.update(newEvent) > 0) {
			events.set(select, newEvent);
			showMessage("Modify Event Successfully!");
		} else
			showMessage("Modify Event Failed!");
		eventPanel.getEventTableModel().setData(events);
		eventDao.closeConnection();
	}

	public void removeEvent() {
		int select = eventPanel.getEventTable().getSelectedRow();
		List<Event> events = getUser().getEvents();
		if (select < 0 || select >= events.size())
			return;
		Event event = events.get(select);
		EventDao eventDao = new EventDao();
		if (eventDao.delete(event) > 0) {
			events.remove(select);
			showMessage("Remove Event Successfully!");
		} else
			showMessage("Remove Event Failed!");
		eventPanel.getEventTableModel().setData(events);
		eventDao.closeConnection();
	}

	private void setEventToPanel(Event event) {
		// TODO Auto-generated method stub
		eventPanel.getEventNameField().setText(event.getEventName());
		int hour, minute;
		String time = event.getEventTime().toString();
		hour = Integer.parseInt(time.substring(0, 2));
		minute = Integer.parseInt(time.substring(3, 5));
		eventPanel.getHourComboBox().setSelectedIndex(hour);
		eventPanel.getMinuteComboBox().setSelectedIndex(minute);
		// set the value of recycle
		int re = event.getEventRecycle();
		eventPanel.getMonCheckBox().setSelected(re % 2 == 1 ? true : false);
		eventPanel.getTueCheckBox().setSelected(re / 2 % 2 == 1 ? true : false);
		eventPanel.getWedCheckBox().setSelected(re / 4 % 2 == 1 ? true : false);
		eventPanel.getThuCheckBox().setSelected(re / 8 % 2 == 1 ? true : false);
		eventPanel.getFriCheckBox()
				.setSelected(re / 16 % 2 == 1 ? true : false);
		eventPanel.getSatCheckBox()
				.setSelected(re / 32 % 2 == 1 ? true : false);
		eventPanel.getSunCheckBox()
				.setSelected(re / 64 % 2 == 1 ? true : false);

		eventPanel.getIntroductionArea().setText(event.getEventIntroduction());
		eventPanel.getSoundCheckBox().setSelected(
				event.getIsSoundAlert() == 1 ? true : false);
		eventPanel.getFileField().setText(event.getSoundFilePath());
		eventPanel.getWindowCheckBox().setSelected(
				event.getIsWindowAlert() == 1 ? true : false);
	}

	private void setSoundFile() {
		// TODO Auto-generated method stub
		FileDialog fileDialog = new FileDialog(taskFrame);
		fileDialog.setVisible(true);
		String filePath = fileDialog.getDirectory() + fileDialog.getFile();
		eventPanel.getFileField().setText(filePath);
	}

	private void showMessage(String message) {
		JOptionPane.showMessageDialog(null, message);
	}

	public void valueChanged(ListSelectionEvent event) {
		// TODO Auto-generated method stub
		if (event.getSource() == eventPanel.getEventTable().getSelectionModel()) {
			eventTableIsChosen();
		}
	}

}
